<template>
  <div class="main">
    <!-- 搜索栏 -->
    <el-card class="tableSearch">
      <el-form :model="searchParams" :inline="true" class="search-form">
        <el-form-item label="标题:" prop="title">
          <el-input
            v-model="searchParams.title"
            placeholder="请输入题目标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="题号:" prop="questionNumber">
          <el-input
            v-model="searchParams.questionNumber"
            placeholder="请输入题号"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="searchButton" type="primary" @click="handleSearch"
            >搜索</el-button
          >
          <el-button class="searchButton" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格区域 -->
    <el-card class="tableDiv">
      <div class="table-toolbar">
        <el-button class="tabbleBu" type="primary" @click="handleAdd">
          <el-icon size="15"><Plus /></el-icon>新增
        </el-button>
        <el-button class="tabbleBu" type="warning" @click="handleEdit">
          <el-icon><Edit /></el-icon>编辑
        </el-button>
        <el-button class="tabbleBu" type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </div>
      <el-table
        :data="tableData"
        height="100%"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="标题" width="180" >
          <template #default="scope">
            <el-link href="https://element-plus.org" target="_blank" :underline="false">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        
        <el-table-column prop="questionNumber" label="题号" width="180" />
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            <span>{{ typeChange(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="knowledges" label="知识点" >
          <template #default="scope">
            <el-tag :type="selectColor(item)" style="margin-left: 5px;" size="large" v-for="item in stringToList(scope.row.knowledges)">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度等级" >
          <template #default="scope">
            <el-tag :type="selectColor(scope.row.difficulty)" style="margin-left: 5px;" size="large" >{{ scope.row.difficulty }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[1, 20, 50, 100]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
    <!-- 增加题目表单 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增题目"
      width="65%"
      :before-close="dialogClose"
    >
      <el-form :inline="true" :model="questionForm">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="questionForm.title"
            placeholder="请输入题目标题"
            style="width: 250px"
          ></el-input>
        </el-form-item>
        <el-form-item label="题号" prop="questionNumber">
          <el-input
            v-model="questionForm.questionNumber"
            placeholder="请输入题号"
            style="width: 100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="知识点" prop="knowledges">
          <el-input
            v-model="questionForm.knowledges"
            placeholder="请输入知识点"
            style="width: 100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="难度等级" prop="difficulty">
          <el-input
            v-model="questionForm.difficulty"
            placeholder="请输入难度等级"
            style="width: 100px"
          ></el-input>
        </el-form-item>
        <el-tabs v-model="questionForm.type" class="" @tab-change="handleClick">
          <el-tab-pane label="单选题" :name="0">




            <!-- 添加选项 -->
            <span>题目内容:</span>
            <MdEditor
              v-model="questionForm.content"
              style="height: 200px; margin-top: 10px"
            ></MdEditor>
            <div style="margin-top: 15px">
              <span style="margin-top: 20px">题目选项:</span>
              <el-button
                style="float: right"
                @click="options.push({})"
                type="primary"
                >添加选项</el-button
              >
            </div>
            <el-radio-group v-model="radio1" @change="optionsChange">
              <div v-for="(item, index) in options" :key="index">
                <el-tag style="margin-top: 10px;" effect="dark" >选项{{ index + 1 }}</el-tag>
                <el-row>
                  <el-col :span="20">
                    <MdEditor
                      v-model="item.title"
                      style="height: 150px; margin-top: 10px;"
                    ></MdEditor>
                  </el-col>
                  <el-col :span="2" style="display: flex; align-items: center">
                    <el-radio
                      size="large"
                      style="margin-left: 10px"
                      :value="index"
                      >是否正确</el-radio
                    >
                  </el-col>
                  <el-col :span="2" style="display: flex; align-items: center;">
                    <el-button @click="options.splice(index,1)" size="small" style="margin-left: 25px;" type="danger" :icon="Delete" circle />
                  </el-col>
                </el-row>
              </div>
            </el-radio-group>
          </el-tab-pane>




          <!-- 判断题 -->
          <el-tab-pane label="判断题" :name="1">
            <span>题目内容:</span>
            <MdEditor
              v-model="questionForm.content"
              style="height: 200px; margin-top: 10px"
            ></MdEditor>
            <el-radio-group v-model="radio1" @change="optionsChange">
              <div v-for="(item, index) in options" :key="index">
                <el-tag style="margin-top: 10px;" effect="dark" >选项{{ index + 1 }}</el-tag>
                <el-row>
                  <el-col :span="23">
                    <MdEditor
                      v-model="item.title"
                      style="height: 150px; margin-top: 10px;"
                    ></MdEditor>
                  </el-col>
                  <el-col :span="1" style="display: flex; align-items: center">
                    <el-radio
                      size="large"
                      style="margin-left: 10px"
                      :value="index"
                      >是否正确</el-radio
                    >
                  </el-col>
                </el-row>
              </div>
            </el-radio-group>
          </el-tab-pane>




          <!-- 多选题 -->
          <el-tab-pane label="多选题" :name="2">
            <span>题目内容:</span>
            <MdEditor
              v-model="questionForm.content"
              style="height: 200px; margin-top: 10px"
            ></MdEditor>
            <div style="margin-top: 15px">
              <span style="margin-top: 20px">题目选项:</span>
              <el-button
                style="float: right"
                @click="options.push({})"
                type="primary"
                >添加选项</el-button
              >
            </div>
         
              <div v-for="(item, index) in options" :key="index">
                <el-tag style="margin-top: 10px;" effect="dark" >选项{{ index + 1 }}</el-tag>
                <el-row>
                  <el-col :span="20">
                    <MdEditor
                      v-model="item.title"
                      style="height: 150px; margin-top: 10px;"
                    ></MdEditor>
                  </el-col>
                  <el-col :span="2" style="display: flex; align-items: center">
                    <el-checkbox style="margin-left: 10px;" v-model="item.isCorrect" :true-value="1" :false-value="0" label="是否正确" size="large" />
                  </el-col>
                  <el-col :span="2" style="display: flex; align-items: center;">
                    <el-button @click="options.splice(index,1)" size="small" style="margin-left: 25px;" type="danger" :icon="Delete" circle />
                  </el-col>
                </el-row>
              </div>
           
          </el-tab-pane>




          <!-- 编程题 -->
          <el-tab-pane label="编程题" :name="4">
            <span>题目内容:</span>
            <MdEditor
              v-model="questionForm.content"
              style="height: 200px; margin-top: 10px"
            ></MdEditor>
            <span style="margin-top: 10px; display: block;">输入格式:</span>
            <MdEditor
              v-model="questionForm.inputFormat"
              style="height: 200px; margin-top: 10px"
            ></MdEditor>
            <span style="margin-top: 10px; display: block;">输出格式:</span>
            <MdEditor
              v-model="questionForm.outputFormat"
              style="height: 200px; margin-top: 10px"
            ></MdEditor>
            <div style="display: flex;margin-top: 10px;" >
              <el-button
                style="margin-left: auto;"
                @click="questionSampleList.push({})"
                type="primary"
                >添加样例</el-button
              >
            </div>
           
            <div v-for="(item,index) in questionSampleList" :key="index">
              
              <el-divider  style="margin-top: 10px;" content-position="center"><el-tag effect="dark" >#样例{{ index + 1 }}</el-tag></el-divider>
              <el-row style="margin-top: 10px;">
              <el-col :span="11">
                <el-input  type="textarea" resize="none" v-model="item.inputSample" class="questionInputOrOutput" placeholder="输入样例" />
              </el-col>
              <el-col :span="2" style="display: flex; align-items: center;">
                <el-button  text @click="questionSampleList.splice(index,1)" style="margin-left: 25px;" :icon="Delete" circle />
              </el-col>
              <el-col :span="11">
                <el-input type="textarea" resize="none" v-model="item.outputSample" class="questionInputOrOutput" placeholder="输出样例" />
              </el-col>
            </el-row>
            </div>
            <div style="display: flex; margin-top: 20px">
              <el-button
                style="margin-left: auto;"
                @click="questionTestCaseList.push({})"
                type="primary"
                >添加测试点</el-button
              >
            </div>
            

            <div v-for="(item,index) in questionTestCaseList" :key="index" style="margin-top: 10px;">
              <el-divider  style="" content-position="center"><el-tag type="danger" effect="dark" >#测试点{{ index + 1 }}</el-tag></el-divider>
              <el-row style="margin-top: 10px;">
              
              <el-col :span="6">
                <el-input  type="textarea" resize="none" v-model="item.inputTestCase" class="questionInputOrOutputTestCase" placeholder="输入样例" />
              </el-col>
              <el-col :span="6">
                <el-input type="textarea" resize="none" v-model="item.outputTestCase" class="questionInputOrOutputTestCase" placeholder="输出样例" />
              </el-col>
              <el-col :span="10" style="display: flex; align-items: center;">
               
               <el-form-item label="时间限制" prop="timeLimit">
                 <el-input
                   v-model="item.timeLimit"
                   placeholder="请输入时间限制"
                   style="width: 100px"
                 ></el-input></el-form-item>
                 <el-form-item label="内存限制" prop="memoryLimit">
                 <el-input
                   v-model="item.memoryLimit"
                   placeholder="请输入时间限制"
                   style="width: 100px"
                 ></el-input>
                
               </el-form-item>
              
             </el-col>
              <el-col :span="2" style="display: flex; align-items: center;">
                <el-button size="small" type="danger"  @click="questionTestCaseList.splice(index,1)" style="margin-bottom: 21px;" :icon="Delete" circle />
              </el-col>
              </el-row>
            </div>
            
            
          </el-tab-pane>




          <!-- 填空题 -->
          <el-tab-pane label="填空题" :name="3">
            <span>题目内容:</span>
            <MdEditor
              v-model="questionForm.content"
              style="height: 200px; margin-top: 10px"
            ></MdEditor>
            <div style="margin-top: 10px;">
              <span>正确答案: </span>
              <el-input v-model="fillQuestionOptionTitle" style="width: 240px" placeholder="输入正确答案" />
            </div>
            
          </el-tab-pane>



        </el-tabs>
       
      </el-form>
      <template #footer>
        <el-button>取消</el-button>
          <el-button
          @click="addQuestion"
          type="primary"
          :loading="loading"
          >新增</el-button
        >
      
        </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { getQuestionByPage } from "@/controller/QuestionController";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { TabPaneName, TabsPaneContext } from "element-plus";
import { MdEditor } from "md-editor-v3";
import {saveQuestion} from "@/controller/QuestionController"
import "md-editor-v3/lib/style.css";


//添加题目的时候题目类型改变触发
const handleClick = (tab: TabPaneName) => {
  //清空选项
 options.value = [];
 questionForm.value.content = "";
 questionForm.value.inputFormat = "";
 questionForm.value.outputFormat = "";
 questionSampleList.value = [];
 questionTestCaseList.value = [];
 //如果为判断题默认增加选项
 if (tab === 1) {
   options.value = [
     {
       title: "正确",
       isCorrect: 1,
     },
     {
       title: "错误",
       isCorrect: 0,
     },
   ];
  }
  if(tab === 3){
    options.value = [
      {
        title: "",
        isCorrect: 1,
      }
    ]
  }
  if(tab === 4){
    questionSampleList.value = [
      {
        inputSample: "",
        outputSample: "",
      }
    ] 
    questionTestCaseList.value = [
      {
        inputTestCase: "",
        outputTestCase: "",
      } 
    ]
  }
};
const searchParams = ref({
  title: "",
  questionNumber: "",
});

const loading = ref(false);
const fillQuestionOptionTitle = ref("");
//选项数组
const options = ref<TYPE.QuestionOption[]>([]);
const radio1 = ref("1");
const selectedRows = ref<number[]>([]);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
//新增表单
const dialogVisible = ref(false);
//新增表单绑定实体类
const questionForm = ref<TYPE.QuestionDTO>({
  type: 0,
});
//编程题样例
const questionSampleList = ref<TYPE.QuestionSample[]>([]);
const questionTestCaseList = ref<TYPE.QuestionTestCase[]>([]);

//新增题目关闭表单
const dialogClose = () => {
  dialogVisible.value = false;
  // TODO: 实现关闭表单的逻辑
  console.log("关闭表单");
};

//点击是否正确单选框后执行的方法
const optionsChange = (val: any) => {
  options.value.forEach((item) => {
    item.isCorrect = 0;
  });
  options.value[val].isCorrect = 1;
};

//添加题目
const addQuestion = async () => {
  loading.value = true;
  try {
    questionForm.value.options = options.value;
    //填空题的处理
    if (questionForm.value.type === 3) {
      questionForm.value.options = [
        {
          title: fillQuestionOptionTitle.value,
          isCorrect: 1,
        },
      ]; 
    }
    //编程题的处理
    if (questionForm.value.type === 4) {
      questionForm.value.questionSamples = questionSampleList.value;
      questionForm.value.questionTestCases = questionTestCaseList.value;
    }
    //保存
    await saveQuestion(questionForm.value);
  } finally {
    loading.value = false;
  }
}

const getQuestion = async () => {
  const params = {};
  if (searchParams.value.title) {
    params.title = searchParams.value.title;
  }
  if (searchParams.value.questionNumber) {
    params.questionNumber = searchParams.value.questionNumber;
  }
  const res = await getQuestionByPage({
    current: currentPage.value,
    pageSize: pageSize.value,
    params,
  });
  tableData.value = res.data.data.records;
  total.value = res.data.data.total;
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getQuestion();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getQuestion();
};

const handleSearch = () => {
  currentPage.value = 1;
  getQuestion();
};

const handleReset = () => {
  searchParams.value.title = "";
  searchParams.value.questionNumber = "";
  currentPage.value = 1;
  getQuestion();
};

const handleAdd = () => {
  openViewForAddQuestion();
  // TODO: 实现新增功能
  console.log("新增");
};

const handleEdit = () => {
  // TODO: 实现编辑功能
  console.log("编辑");
};

const handleDelete = () => {
  // TODO: 实现删除功能
  console.log("删除");
};
//将类型转化为文本
const typeChange = (type: any) => {
  switch (type) {
    case 0:
      return "单选题";
    case 2:
      return "多选题";
    case 1:
      return "判断题";
    case 3:
      return "填空题";
    case 4:
      return "编程题";
    default:
      return "";
  }
};

const openViewForAddQuestion = () => {
  dialogVisible.value = true;
};
//初始化
onMounted(() => {
  getQuestion();
  console.log(tableData.value);
});
//选择表格
const handleSelectionChange = (val: TYPE.Question[]) => {
  console.log(val.map((row) => row.id));
};

/**
 * 将字符串转换为列表 用于知识点展示
 * @param str 
 */
const stringToList = (str: string) => {
  if (!str) return [];
  const res = str.split(",");
  if (res.length > 3) return res.slice(0, 3);
  return  res
};
/**
 * 知识点颜色
 * @param str 
 */
const selectColor = (str:string)=>{
  if(!str) return "primary";
  const colorList = ["primary","success","info","warning","danger"]
  let v = 0;
  for(let i = 0;i<str.length;i++){
    v += str.charCodeAt(i);
  }
  const index = v%5;
  return colorList[index]
}
</script>
<style scoped>
.main {
  padding: 25px 15% !important;
  height: 100%;
}
.tableDiv {
  border-radius: 18px;
  margin-top: 30px;
}
.tableDiv :deep(.el-table__row) {
      height: 60px;
    }
.tableDiv :deep(.el-table__header th){
      font-size: 17px;
    }
.tableSearch {
  border-radius: 18px;
  padding: 10px;
}
.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.search-form .el-form-item:last-child {
  margin-left: auto;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}
.search-form .el-form-item :deep(.el-form-item__label) {
  font-size: 16px;
  font-weight: bold;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.searchButton {
  border-radius: 10px;
  font-weight: bold;
}
.table-toolbar {
  margin-bottom: 20px;
}
.tabbleBu {
  border-radius: 12px;
}
.addQuestionViewInput {
  width: 300px;
}
.questionInputOrOutput {
  width: 300px;
  height: 100px;
  margin: 0 auto;
  display: block;
}
.questionInputOrOutput :deep(.el-textarea__inner) {
  height: 100px;
  border: 1px solid black;
  border-radius: 8px;
}
.questionInputOrOutput :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}
.questionInputOrOutputTestCase {
  width: 200px;
  height: 100px;
  margin: 0 auto;
  display: block;
}
.questionInputOrOutputTestCase :deep(.el-textarea__inner) {
  height: 100px;
  border: 1px solid black;
  border-radius: 8px;
}
.questionInputOrOutputTestCase :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

</style>
